package ynu.edu.Util;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import ynu.edu.Service.FoxToken;
import org.springframework.stereotype.Component;

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Scanner;

@Component
public class SensorUtil {
    private static final String SENSOR_API_URL = "https://fbox360.com/api/v2/dmon/value/get?boxNo=%s";
    @Resource
    private PropertiesUtil propertiesUtil;
    @Resource
    FoxToken foxToken;

    public List<Double> fetchSensorData(String boxNo, List<String> sensorIds) {
        try {
            String accessToken = getAccessToken();
            while (accessToken == null || isTokenExpired()) {
                accessToken = foxToken.getAccessToken();
            }
            String response = fetchSensorData(boxNo, sensorIds, accessToken);
            return extractValuesFromJson(response);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private List<Double> extractValuesFromJson(String jsonString) throws Exception {
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonArray = objectMapper.readTree(jsonString);
        List<Double> list = new ArrayList<>();
        for (JsonNode element : jsonArray) {
            double value = element.get("value").asDouble();
            list.add(value);
        }
        return list;
    }
    private String getAccessToken() {
        Properties properties = propertiesUtil.loadProperties();
        return properties.getProperty("fox_access_token");
    }

    private boolean isTokenExpired() {
        Properties properties = propertiesUtil.loadProperties();
        String expiresInMillis = properties.getProperty("fox_expires_in");
        if (expiresInMillis == null) {
            return true;
        }
        long expiresAt = Long.parseLong(expiresInMillis);
        return System.currentTimeMillis() >= expiresAt;
    }

    private String fetchSensorData(String boxNo, List<String> sensorIds, String accessToken) throws Exception {
        URL url = new URL(String.format(SENSOR_API_URL, boxNo));
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Authorization", "Bearer " + accessToken);
        connection.setDoOutput(true);

        String jsonInputString = String.format("{\"ids\": %s}", sensorIds.toString().replace("[", "[").replace("]", "]"));

        try (OutputStream os = connection.getOutputStream()) {
            byte[] input = jsonInputString.getBytes("utf-8");
            os.write(input, 0, input.length);
        }

        try (Scanner scanner = new Scanner(connection.getInputStream(), "utf-8")) {
            StringBuilder response = new StringBuilder();
            while (scanner.hasNext()) {
                response.append(scanner.nextLine());
            }
            return response.toString();
        }
    }
}
